pipeline {
    agent any
    parameters {
        string(description: '项目名称，必须全部使用英文',     name: 'add_name', trim: true)
        string(description: '项目git仓库',  name: 'git_url', trim: true)
        choice(description: '项目类型',     name: 'job_type',choices: ['java', 'node'])
        choice(description: '项目平台',     name: 'job_view', choices: ['ruoyi', '其他'])
        string(description: '项目端口',     name: 'job_port', trim: true)
        string(description: '项目中文名',   name: 'job_cname', trim: true)
        string(description: '制品路径',     name: 'project_path', trim: true)
    }
    environment {
        AWS_ACCOUNT_ID = "123456789012"          // 替换为你的AWS账号ID
        AWS_REGION = "us-east-1"                // 替换为你的ECR区域
        ECR_REPO = "${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com"
        IMAGE_TAG = "${env.BUILD_NUMBER}-${env.GIT_COMMIT.take(8)}"  // 镜像Tag格式：构建号-短Commit ID
    }
    stages {
        stage('获取用户信息') {
            steps { /* 同原脚本 */ }
        }
        stage('参数检测') {
            steps { /* 同原脚本 */ }
        }
        stage('自动创建Job') {
            steps {
                script {
                    def jobParams = [
                        add_name: env.add_name,
                        git_url: env.git_url,
                        job_type: env.job_type,
                        job_view: env.job_view,
                        job_port: env.job_port,
                        project_path: env.project_path
                    ]
                    insertDataToMysql(jobParams)
                    createCusJob(env.job_type, env.job_view, env.add_name, env.job_cname)
                }
            }
        }
        stage('构建并推送镜像到ECR') {
            steps {
                script {
                    // 1. 登录AWS ECR
                    withCredentials([[
                        $class: 'AmazonWebServicesCredentialsBinding',
                        credentialsId: 'aws-creds',
                        accessKeyVariable: 'AWS_ACCESS_KEY_ID',
                        secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
                    ]]) {
                        sh """
                            aws ecr get-login-password --region ${AWS_REGION} | \
                            docker login --username AWS --password-stdin ${ECR_REPO}
                        """
                    }

                    // 2. 构建Docker镜像
                    def imageName = "${env.add_name}:${IMAGE_TAG}"
                    def ecrImageUri = "${ECR_REPO}/${env.add_name}:${IMAGE_TAG}"
                    sh "docker build -t ${imageName} -f ${env.project_path}/Dockerfile ${env.project_path}"

                    // 3. 标记并推送镜像
                    sh "docker tag ${imageName} ${ecrImageUri}"
                    sh "docker push ${ecrImageUri}"
                }
            }
        }
        stage('更新K8s清单并提交PR') {
            steps {
                script {
                    // 1. 克隆GitOps仓库（存放K8s YAML的仓库）
                    dir('gitops-repo') {
                        git(
                            url: 'git@gitee.com/giteechaozhi/dev.git',
                            branch: 'main',
                            credentialsId: 'git-ssh-key'
                        )

                        // 2. 修改Deployment的镜像Tag
                        sh """
                            sed -i 's|image: ${ECR_REPO}/${env.add_name}:.*|image: ${ECR_REPO}/${env.add_name}:${IMAGE_TAG}|g' \
                                ${env.add_name}/deployment.yaml
                        """

                        // 3. 创建新分支并提交
                        sh """
                            git checkout -b update-${env.add_name}-${IMAGE_TAG}
                            git add ${env.add_name}/deployment.yaml
                            git commit -m 'Update ${env.add_name} image to ${IMAGE_TAG}'
                            git push origin update-${env.add_name}-${IMAGE_TAG}
                        """

                        // 4. 使用gh CLI创建PR（需提前安装gh）
                        withCredentials([string(credentialsId: 'gitee-token', variable: 'gitee_TOKEN')]) {
                            sh """
                                gh auth login --with-token <<< "${gitee_TOKEN}"
                                gh pr create \
                                    --title "Update ${env.add_name} image (Build ${env.BUILD_NUMBER})" \
                                    --body "Automated by Jenkins. Image: ${ecrImageUri}" \
                                    --base main \
                                    --head update-${env.add_name}-${IMAGE_TAG} \
                                    --reviewer dev-lead,ops-team
                            """
                        }
                    }
                }
            }
        }
    }
    post {
        success {
            slackSend(
                channel: '#deployments',
                message: "✅ 成功构建并提交PR: ${env.add_name} (Image: ${ECR_REPO}/${env.add_name}:${IMAGE_TAG})"
            )
        }
        failure {
            slackSend(
                channel: '#deployments',
                message: "❌ 构建失败: ${env.add_name} (Build ${env.BUILD_NUMBER})"
            )
        }
    }
}

// 以下辅助方法保持不变（原脚本中的方法）
def createCusJob(jobType, view_name, jobName, jobCName) { /* ... */ }
def insertDataToMysql(Map pmap) { /* ... */ }
